// pages/pay/pay.js
const app = getApp();
const api = require('../../utils/api');
const constant = require('../../utils/constant');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //获取全局变量 导航栏的高度statusBarHeight
    statusBarHeight: app.globalData.statusBarHeight,
    // 胶囊
    jiaonang: app.globalData.jiaonang, 
    navigationHeight: app.globalData.navigationHeight,
    BASEURLWWW:constant.BASEURLWWW,
    // 要下单的商品
    chooseGoods:[
      {
        goods_id:1,
        goods_pic:[],
        name: '',
        goods_spec:{},
        num: null
      }
    ],
    // 选择的收货地址id
    newAddressId: null,
    // 收货地址
    address:{},
    // 购物车商品id
    carListIdData:[],
    // 购物车列表数据
    carListData:[],
    // 总价
    totalPrice: 0,
    // 总数量
    total: 0,
    // 订单号
    order_no: '',
    // 是否直接购买，true：是直接购买，false：购物车购买
    isDirect: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let newAddressId = null;
    let orderGoodsIdArr = null;
    let goodsArr = [];
    if(options.addressId){
      newAddressId = options.addressId;
    }
    // 购物车购买
    if(options.orderGoods){
      orderGoodsIdArr = JSON.parse(options.orderGoods);
      this.getcarListData(orderGoodsIdArr);
      this.setData({
        addressId: newAddressId,
        carListIdData: orderGoodsIdArr,
        isDirect: false
      })
    }
    // 商品详情立即购买
    if(options.goods){
      let goods = JSON.parse(options.goods);
      let totalPrice = 0;
      let total = 0;
      goodsArr.push(goods);
      totalPrice += goods.price*goods.goods_num;
      total = goods.goods_num;
      this.setData({
        addressId: newAddressId,
        carListData: goodsArr,
        totalPrice,
        total,
        isDirect: true
      })
    }
    
  },
  // 获取购物车列表数据
  getcarListData:function(orderGoodsIdArr){
    api.carList(orderGoodsIdArr).then(res => {
      if(res.code == 0){
        if(res.data.data){
          this.handleCarGoodsStatus(res.data.data);
        }
      }
    })
  },
  // 获取用户地址
  getAddress:function(){
    let newAddressId = this.data.addressId;
    let addressIdArr = [];
    api.getAddress().then(res => {
      if(res.code == 0){
        res.data.data.forEach(item => {
          // 如果选择了地址
          if(newAddressId && newAddressId == item.address_id){
            addressIdArr.push(item);
          }else{
            if(item.defaualt == 1){
              addressIdArr.push(item)
            }
          }
        })
        if(addressIdArr.length > 0){
          this.setData({
            address: addressIdArr[0]
          })
        }else{
          if(res.data.data.length > 0){
            this.setData({
              address: res.data.data[0]
            })
          }else{
            this.setData({
              address: null
            })
          }
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getAddress();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  // 返回上一级
  back:function(){
    if(this.data.isDirect){
      let goodsId = this.data.carListData[0].goods_id;
      wx.reLaunch({
        url: '/pages/goods/goods?goods_id='+ goodsId
      })
    }else{
      wx.reLaunch({
        url: '/pages/car/car'
      })
    }
  },
  
  // 购物车商品状态判断
  handleCarGoodsStatus:function(carListData){
    if(carListData.length > 0){
      carListData.forEach(item => {
        // 商品是否被删除(数据不存在):不显示
        if(item.goods){
          item.isShow = true;
          // 商品是否是单品
          if(item.sku){
            item.isSku = true;
            // 不是单品，是否可以下单
            if(item.key_name == item.sku.key_name && item.key_value == item.sku.key_value){
              // 是否可下单
              item.isBuy = true;
            }else{
              item.isBuy = false;
            }
          }else{
            item.isSku = false;
            // 是单品，是否可以下单
            if(item.price == item.goods.shop_price){
              item.isBuy = true;
            }else{
              item.isBuy = false;
            }
          }
        }else{
          item.isShow = false;
        }
      })
      this.setData({
        carListData,
      });
    }
    
    // 打印购物车列表数据/可下单商品个数/可操作商品个数
    // console.log('查看购物车列表',this.data.carListData);
    // 计算总价和总量
    this.countTotal();
  },
  // 计算总价
  countTotal:function(){
    let carListDataArr = this.data.carListData;
    let totalPrice = 0;
    let total = 0;
    carListDataArr.forEach(item => {
      if(item.goods){
        // 已选并可下单
        if(item.isBuy){
          if(item.isSku){ // 非单品价格
            totalPrice += item.sku.price*item.goods_num;
          }else{ // 单品价格
            totalPrice += item.goods.shop_price*item.goods_num;
          }
          total += item.goods_num;
        }
      }
      
    })
    this.setData({
      totalPrice,
      total
    })
  },
  // 跳转到地址选择carListIdData
  jumpToAddress: function(){
    let isDirect = this.data.isDirect;
    if(isDirect){ // 商品详情直接购买
      let goods = this.data.carListData[0];
      wx.navigateTo({
        url: `/pages/address/address?chooes=true&goods=${JSON.stringify(goods)}`
      })
    }else{ // 购物车购买
      let carListIdDataArr = this.data.carListIdData;
      wx.navigateTo({
        url: `/pages/address/address?chooes=true&carListIdData=${JSON.stringify(carListIdDataArr)}`
      })
    }
    
  },
  // 支付
  toPay:function(){
    let carListData = this.data.carListData;
    let address = this.data.address;
    let old_goods = [];
    let userInfo = {};
    if(this.data.isDirect){
      carListData.forEach(item => {
        old_goods.push({
          goods_id: item.goods_id,
          key_name: item.key_name,
          goods_num: item.goods_num,
        })
      })
    }else{
      carListData.forEach(item => {
        if(item.isBuy){
          if(item.isSku){// 非单品
            old_goods.push({
              goods_id: item.goods_id,
              key_name: item.sku.key_name,
              goods_num: item.goods_num,
            })
          }else{
            old_goods.push({
              goods_id: item.goods_id,
              goods_num: item.goods_num,
            })
          }
        }
      })
    }
    
    userInfo.consignee = address.consignee; // 收件人
    userInfo.mobile = address.mobile; // 手机号
    userInfo.region = address.region; // 省市区
    userInfo.address = address.address; // 详细地址
    userInfo.zipcode = ''; // 邮编
    userInfo.tel = ''; // 座机
    userInfo.buyer_remark = ''; // 买家备注
    userInfo.source = 2
    // 创建订单
    api.creatOrder(old_goods,userInfo).then(res => {
      if(res.code == 0){
        let order_no = res.data.data.order_no;
        this.setData({
          order_no
        })
        wx.login({
          success: res => {
            // 发送 res.code 到后台换取 openId, sessionKey, unionId
            // console.log('wx.login',res);
            if(res.code && res.code != ''){
              api.getPayOptions(res.code,order_no).then(res => {
                if(res.code == 0){
                  wx.requestPayment(
                    {
                    'timeStamp': res.data.data.timeStamp,
                    'nonceStr': res.data.data.nonceStr,
                    'package': res.data.data.package,
                    'signType': res.data.data.signType,
                    'paySign': res.data.data.paySign,
                    'success':function(res){
                      wx.showToast({
                        title: 'title',
                        icon: 'success',
                        success: function(){
                          wx.reLaunch({
                            url: '/pages/order/order?current=2'
                          })
                        }
                      })
                    },
                    'fail':function(res){
                      wx.reLaunch({
                        url: '/pages/order/order?current=1'
                      })
                    },
                    'complete':function(res){

                    }
                    })
                }
              })
            }
          },
          fail:res => {

          }
        })
      }else{
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
    })
  }
})